<?php

namespace App\Api\Fibrpro;

use PhalApi\Api;
use App\Domain\User\User as UserDomain;
use PhalApi\Exception\BadRequestException;
use PhpOffice\PhpWord\TemplateProcessor;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

use Qiniu\Auth;


/**
 * fibrpro报价单生成
 *   @desc 报价单
 */
class Price extends Api
{

    public function getRules()
    {
        return array(
            'po' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => 'id'),
            ),
        );
    }

    /**
     * 通过id生成po
     * @desc 订单word
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function po()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $id = $this->id;   // 账号参数

        $price = \PhalApi\DI()->notorm
            ->fibrpro_price
            ->where('id', $id)
            ->fetchOne();

        if ($price) {
            $form = json_decode($price['form_json'], true);
        }
        // return $form;
        if( $form['format'] == 'Non-CITF' ){
            $word = new TemplateProcessor('templates/Quotation_FIBRPRO_Non_CITF.docx');
        }else if( $form['format'] == 'CITF' ){
            $word = new TemplateProcessor('templates/Quotation_FIBRPRO.docx');
        }

        // $word = new TemplateProcessor('templates/Quotation_FIBRPRO.docx');

        if ($form['sexP']) {
            $form['sexTtitle'] = $form['sexP'];
            $form['sex'] = $form['sexP'];
        }

        if( $form['formTotal']['amountdiscount'] > 0 ){
            $form['amountdiscount_'] = '-' . number_format($form['formTotal']['amountdiscount'], 2, '.', ',');
        }else{
            $word->deleteRow('amountdiscount_', array($form['formTotal']['amountdiscount'])); // 删除行
        }

        if($form['formTotal']['amount']){
            $form['amount_'] = number_format($form['formTotal']['amount'], 2, '.', ',');
        }

        if( $form['companyfax_']){
            // 使用正则表达式去除字符串中的/n，并替换为换行符
            $form['companyfax_'] = preg_replace('/\/n/', "\n", $form['companyfax_']);
        }


        if (is_array($form['who']) && count($form['who']) > 1) {
            $form['whoPrint'] = 'Elvin Tang';
            $form['whoTitle'] = 'Marketing Manager';
        } elseif (is_array($form['who']) && in_array('ET', $form['who'])) {
            $form['whoPrint'] = 'Elvin Tang';
            $form['whoTitle'] = 'Marketing Manager';
        } elseif (is_array($form['who']) && in_array('TW', $form['who'])) {
            $form['whoPrint'] = 'Director';
            $form['whoTitle'] = 'Dr. Tin Wong';
        }

        if ($form['formDelivery']['deliverytripQTY'] > 0) {
            $num = $form['formDelivery']['deliverytripQTY'];
            $numWords = [
                1 => 'ONE',
                2 => 'TWO',
                3 => 'THREE',
                4 => 'FOUR',
                5 => 'FIVE',
                6 => 'SIX',
                7 => 'SEVEN',
                8 => 'EIGHT',
                9 => 'NINE',
                10 => 'TEN'
            ];
            $englishNum = isset($numWords[$num]) ? $numWords[$num] : $num;
            $form['Delivery_'] = $englishNum . ($num > 1 ? ' lots' : ' lot');
        }

        if ($form['formDelivery']['Validity']) {
            $form['Validity'] = $form['formDelivery']['Validity'];
        }
        if (isset($form['formTotal']['deposit'])) {
            $form['rate'] = $form['formTotal']['deposit'];
            $form['rate_'] = 100 - $form['rate'];
        }

        foreach ($form as $key => $value) {
            if (strpos($value, 'http') === false) {
                if ($value) {
                    $word->setValue($key, $value);
                } else {
                    $word->setValue($key, ''); // 替换文本内容
                }
            }
        }

        if ($form['title'] == 'Synthetec® Stone Grating') {
            $word->setValue('r_', '®');
            $word->setValue('title_', 'Synthetec');
        } else {
            $word->setValue('r_', "");
            $word->setValue('title_', "Synthetic");
        }


        $products = $form['SelectedProducts'];
        // 遍历 SelectedProducts 数组
        foreach ($form['SelectedProducts'] as $key => $product) {
            // 单独检查 moldtotal 是否为空
            if (!($product['total'])) {
                // 如果为空，则赋值为 "RATE ONLY"
                $form['SelectedProducts'][$key]['total_'] = "RATE ONLY";
            }
            // 单独检查 quality 是否为空
            if (empty($product['quality']) || $product['quality'] === '0') {
                $form['SelectedProducts'][$key]['quality_'] = "RATE ONLY";
            }
            if( $product['level'] == "Other" ){
                $form['SelectedProducts'][$key]['level'] = $product['level_Other'];
            }
        }
        // 产品
        $word->cloneRowAndSetValues('productIndex', $form['SelectedProducts']);


        // return array($form['formMold']);
        if ($form['formMold'] && $form['formMold']['moldcharge']) {
            $form['formMold']['moldQTY'] =  $form['formMold']['moldQTY'] ?  $form['formMold']['moldQTY'] : 'RATE ONLY';
            $form['formMold']['moldtotal_'] =  $form['formMold']['moldtotal'] ?  $form['formMold']['moldtotal_'] : 'RATE ONLY';
            $word->cloneRowAndSetValues('moldindex', array($form['formMold']));
        } else {
            $word->deleteRow('moldindex'); // 删除行
        }
        // 设计
        if ($form['formColor'] && $form['formColor']['colorcharge']) {

            $form['formColor']['colorunitrate_'] = number_format($form['formColor']['colorunitrate'], 2, '.', ','); // 保留两位小数，四舍五入
            $form['formColor']['colortotal_'] = number_format($form['formColor']['colortotal'], 2, '.', ','); // 保留两位小数，四舍五入

            $form['formColor']['colorQTY'] =  $form['formColor']['colorQTY'] ?  $form['formColor']['colorQTY'] : 'RATE ONLY';
            $form['formColor']['colorunitrate_'] =  $form['formColor']['colorunitrate_'] ?  $form['formColor']['colorunitrate_'] : 'RATE ONLY';
            $form['formColor']['colortotal_'] =  $form['formColor']['colortotal'] ?  $form['formColor']['colortotal_'] : 'RATE ONLY';
            
            $word->cloneRowAndSetValues('colorindex', array($form['formColor']));
        } else {
            $word->deleteRow('colorindex'); // 删除行
        }

        // 运输
        $form['formDelivery']['deliverytripprice_'] = number_format($form['formDelivery']['deliverytripprice'], 2, '.', ',');
        $form['formDelivery']['deliverytotal_'] = number_format($form['formDelivery']['deliverytotal'], 2, '.', ',');
        $word->cloneRowAndSetValues('deliveryindex', array($form['formDelivery']));

        $word->setImageValue('sign', $form['sign']);

        $form['sImg_'] = "https://img.wenfree.cn/images/fibrpro/et.png";
        if (is_array($form['who']) && count($form['who']) > 1) {
            $form['sImg'] = 'https://img.wenfree.cn/images/fibrpro/et%2Btw.png';
            $form['pImg'] = 'https://img.wenfree.cn/images/fibrpro/et%2Btw.png';
            $form['sign'] = 'https://img.wenfree.cn/images/fibrpro/et-sign.png';
        } elseif (is_array($form['who']) && in_array('ET', $form['who'])) {
            $form['sImg'] = 'https://img.wenfree.cn/images/fibrpro/et.png';
            $form['pImg'] = 'https://img.wenfree.cn/images/fibrpro/et.png';
            $form['sign'] = 'https://img.wenfree.cn/images/fibrpro/et-sign.png';
        } elseif (is_array($form['who']) && in_array('TW', $form['who'])) {
            $randomInt = rand(1, 29);
            $form['sImg'] = 'https://img.wenfree.cn/images/fibrpro/tw.png';
            $form['pImg'] = 'https://img.wenfree.cn/images/fibrpro/tw.png';
            $form['sign'] = 'https://img.wenfree.cn/images/fibrpro/sign' . $randomInt . '.png';
        }

        $word->setImageValue('pImg', $form['pImg']);
        $word->setImageValue('sImg_', $form['pImg']);

        // $wordPath = "template/" . "FIBRPRO-" . $price['id'] . '-' . $price['name'] . time() . ".docx";
        // $word->saveAs($wordPath);

        $wordPath = "template/". $price['name'] . ".docx";
        $word->saveAs($wordPath);

        $url = "https://api.wenfree.cn/" . $wordPath;

        // return [$url, $form];
        return array(
            "url" => $url, 
            "msg" => "done", 
            "form" => $form,
        ); //返回word路径，前端下载
    }

    
   
}
